package com.jinjiafeng.framelibrary.skin.support;

import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;

import com.jinjiafeng.framelibrary.skin.attr.SkinAttr;
import com.jinjiafeng.framelibrary.skin.attr.SkinType;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by jinjiafeng.
 * date:on 18-5-9
 */

public class SkinAttrSupport {

    /**
     * 解析控件属性进List<SkinAttr>存储
     *
     * @param attrs 控件属性
     */
    public static List<SkinAttr> getSkinAttrs(Context context, AttributeSet attrs) {
        ArrayList<SkinAttr> skinAttrs = new ArrayList<>();
        int attributeCount = attrs.getAttributeCount();
        for (int index = 0; index < attributeCount; index++) {
            String attributeName = attrs.getAttributeName(index);
            SkinType skinType = getSkinType(attributeName);
            if (skinType != null) {
                String attributeValue = attrs.getAttributeValue(index);
                String resName = getResName(context, attributeValue);
                if (TextUtils.isEmpty(resName)) {
                    continue;
                }
                SkinAttr skinAttr = new SkinAttr(resName, skinType);
                skinAttrs.add(skinAttr);
            }
        }
        return skinAttrs;
    }

    private static SkinType getSkinType(String attributeName) {
        final SkinType[] values = SkinType.values();
        for (SkinType value : values) {
            if (attributeName.equals(value.getType())) {
                return value;
            }
        }
        return null;
    }

    private static String getResName(Context context, String attributeValue) {
        if (attributeValue.startsWith("@")) {
            int resId = Integer.parseInt(attributeValue.substring(1));
            return context.getResources().getResourceEntryName(resId);
        }
        return "";
    }
}
